package pl.com.like.sequoia.web.servlets;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import pl.com.like.sequoia.model.bio.BioObjectAlign;
import pl.com.like.sequoia.model.bio.BioObjectHandler;
import pl.com.like.sequoia.web.service.ISearchService;
import pl.com.like.sequoia.web.vo.SearchType;

public class DownloadServlet extends HttpServlet {

	public static final String OBJECT_ID = "objectId";
	public String contentType = "application/octet-stream";
	private final static Logger log = LoggerFactory.getLogger(DownloadServlet.class);

	private static final long serialVersionUID = 3L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		processRequest(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		processRequest(req, resp);
	}

	public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		ByteArrayDataSource document = null;
		OutputStream out = null;

		try {
			out = response.getOutputStream();
			ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
			if (null != context) {
				// set webManager
				ISearchService searchService = (ISearchService) context.getBean("searchService");
				String idObject = request.getParameter(DownloadServlet.OBJECT_ID);
				if (idObject == null || idObject.isEmpty()) {
					return;
				}
				String filePath = null;
				BioObjectAlign align = searchService.getAlign(idObject);
				if (align != null) {
					filePath = align.getPath();
				} else {
					BioObjectHandler result = searchService.findBioObject(idObject, SearchType.PDB);
					if (result != null) {
						filePath = result.getPath();
					}
				}
				if (filePath != null) {
					document = new ByteArrayDataSource(new FileInputStream(filePath), contentType, idObject);
					response.setContentType(document.getContentType());
					response.setHeader("Content-Disposition", "inline;filename=" + idObject);
					response.setContentLength(document.size());
					out.write(document.toByteArray());
				} else {
					log.warn("requested object {} do not exist in local database", idObject);
					return;
				}
			} else {
				throw new ServletException("cannot initialize web context in servlet");
			}
		} catch (IOException e) {
			String msg = "error in opening open stream";
			log.error(msg, e);
			e.printStackTrace(new PrintStream(out));
			throw new ServletException(msg, e);
		} catch (Exception e) {
			String msg = "error in init SearchService";
			log.error(msg, e);
			e.printStackTrace(new PrintStream(out));
			throw new ServletException(msg, e);
		} finally {
			out.close();
		}
	}
}
